import { Index, JoinColumn, OneToMany, ViewColumn, ViewEntity } from 'typeorm';

import { Department } from '@/dingding/department/entities/department.entity';

@ViewEntity({
  name: 'crm_member_node_view',
  expression: `
    SELECT cmm.id,
      cmm.position,
      cmm.name,
      cmm.phone,
      cmm.remark,
      cmm.status,
      cmm.user_id,
      cmm.boss,
      cmm.admin,
      cmm.leader,
      cmm.dept_id_list,
      cmm.email,
      cmm.org_email,
      cmm.avatar,
      cmm.finance,
      cmm.member_position,
      cmm.ding_user_id,
      GROUP_CONCAT(cdd.display_name) AS dept_name_list
    FROM crm_member cmm
    JOIN crm_ding_dept cdd ON FIND_IN_SET(cdd.id, cmm.dept_id_list) > 0
    GROUP BY id;
  `,
})
export class Member {
  @Index('member_id_index', { unique: true })
  @ViewColumn()
  id: string;

  @Index('member_ding_user_id_index', { unique: true })
  @ViewColumn()
  dingUserId: string;

  @Index('member_user_id_index', { unique: true })
  @ViewColumn()
  userId: string;

  @ViewColumn()
  /** 职位 */
  position: string;

  @ViewColumn()
  /** 名字 */
  name: string;

  @ViewColumn()
  /** 状态 1:在职 0:离职 */
  status: 1 | 0;

  @ViewColumn()
  /** 所属部门id列表 */
  deptIdList: string;

  @ViewColumn()
  @OneToMany(() => Department, (department) => department.displayName)
  @JoinColumn({ name: 'deptNameList' })
  /** 所属部门id列表 */
  deptNameList: string;

  @ViewColumn()
  /** 职位 */
  memberPosition: number;

  @ViewColumn()
  phone: string;

  @ViewColumn()
  remark: string;

  @ViewColumn()
  boss: boolean;

  @ViewColumn()
  admin: boolean;

  @ViewColumn()
  leader: boolean;

  @ViewColumn()
  email: string;

  @ViewColumn()
  orgEmail: string;

  @ViewColumn()
  avatar: string;

  @ViewColumn()
  finance: boolean;
}
